package com.dge.common.widgets

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.os.CountDownTimer
import android.util.AttributeSet
import android.view.View
import com.dge.common.R
import com.dge.common.extentions.dp
import timber.log.Timber

class CircleProgressBar(context: Context, attrs: AttributeSet) : View(context, attrs) {
    // 画圆环的画笔
    private var ringPaint: Paint? = null
    private var ringBGPaint: Paint? = null

    //    // 画字体的画笔
    //    private Paint textPaint;
    // 圆环颜色
    private var ringColor = 0

    //    // 字体颜色
    //    private int textColor;
    // 半径
    private var radius = 0f
    private val smallCirclePathRadiusPlus: Float

    // 圆环宽度
    private var strokeWidth = 0f

    //    // 字的长度
    //    private float txtWidth;
    //    // 字的高度
    //    private float txtHeight;
    // 总进度
    private var totalProgress: Long = 100

    //画小圆的实心的画笔
    private var smallCircleSolidePaint: Paint? = null

    // 当前进度
    private var currentProgress: Long = 0
    private val alpha = 25 //透明度

    //额外距离
    private val extraDistance = 0.7f
    private val smallCircleRadius: Float
    private val smallCirclePadding: Float
    private var timer: CountDownTimer? = null
    private fun initAttrs(context: Context, attrs: AttributeSet) {
        val typeArray =
            context.theme.obtainStyledAttributes(attrs, R.styleable.CircleProgressbar, 0, 0)
        radius = typeArray.getDimension(R.styleable.CircleProgressbar_radius, 80f)
        strokeWidth = typeArray.getDimension(R.styleable.CircleProgressbar_strokeWidth, 10f)
        ringColor = typeArray.getColor(R.styleable.CircleProgressbar_ringColor, 0xFF0000)
        //        textColor = typeArray.getColor(R.styleable.CircleProgressbar_textColor, 0xFFFFFF);
        typeArray.recycle()
    }

    private fun initVariable() {
        ringPaint = Paint()
        ringPaint!!.isAntiAlias = true
        ringPaint!!.isDither = true
        ringPaint!!.color = ringColor
        ringPaint!!.style = Paint.Style.STROKE
        ringPaint!!.strokeCap = Paint.Cap.ROUND
        ringPaint!!.strokeWidth = strokeWidth
        ringPaint!!.setShadowLayer(15.0f, 0f, 0f, ringColor)
        ringBGPaint = Paint()
        ringBGPaint!!.isAntiAlias = true
        ringBGPaint!!.isDither = true
        ringBGPaint!!.color = Color.parseColor("#EFEFF4")
        ringBGPaint!!.style = Paint.Style.STROKE
        ringBGPaint!!.strokeCap = Paint.Cap.ROUND
        ringBGPaint!!.strokeWidth = strokeWidth
        smallCircleSolidePaint = Paint()
        smallCircleSolidePaint!!.isAntiAlias = true
        smallCircleSolidePaint!!.isDither = true
        smallCircleSolidePaint!!.style = Paint.Style.FILL
        smallCircleSolidePaint!!.color = context.resources.getColor(R.color.white)
        //        textPaint = new Paint();
//        textPaint.setAntiAlias(true);
//        textPaint.setStyle(Paint.Style.FILL);
//        textPaint.setColor(textColor);
//        textPaint.setTextSize(radius / 2);
//        Paint.FontMetrics fm = textPaint.getFontMetrics();
//        txtHeight = fm.descent + Math.abs(fm.ascent);
    }

    override fun onDraw(canvas: Canvas) {
        val oval =
            RectF(width / 2 - radius, height / 2 - radius, width / 2 + radius, height / 2 + radius)
        canvas.drawArc(oval, 0f, 0f, false, ringBGPaint!!)
        canvas.drawArc(oval, -90f, 360f, false, ringBGPaint!!)
        if (currentProgress >= 0) {
            val currentAngle = currentProgress.toFloat() / totalProgress * 360
            //            #FFAF31  #FE7E28
            val rate = currentProgress.toFloat() / totalProgress
            var red = Integer.toHexString((0xff - rate * (0xff - 0xfE)).toInt())
            if (red.length == 1) {
                red = "0$red"
            }
            var green = Integer.toHexString((0xAF - rate * (0xAF - 0x7E)).toInt())
            if (green.length == 1) {
                green = "0$green"
            }
            var blue = Integer.toHexString((0x31 - rate * (0x31 - 0x28)).toInt())
            if (blue.length == 1) {
                blue = "0$blue"
            }
            val color = "#$red$green$blue"
            if (color.length == 7) {
                ringPaint!!.color = Color.parseColor(color)
                ringPaint!!.setShadowLayer(15.0f, 0f, 0f, Color.parseColor(color))
                //Timber.d( "color = " + color + "; red = " + red + "; green = " + green + "; blue = " + blue + "; rate = " + rate);
//            ringPaint.setColor(Color.parseColor(color));
//            ringPaint.setColor(((int) (rate * (0xff - 0xfB))) << 3 + 0xfb0000 + (int) ((1 - rate) * 0x96) << 1 + (int) ((1 - rate) * 0x34));
//                ringPaint.setAlpha((int) (alpha + ((float) currentProgress / totalProgress) * 230));
                canvas.drawArc(oval, 0f, 0f, false, ringPaint!!)
                canvas.drawArc(oval, -90f, currentAngle, false, ringPaint!!)
                //画小圆
                val smallRadius = smallCircleRadius - smallCirclePadding
                val currentDegreeFlag = currentAngle + extraDistance
                val arc = Math.abs(Math.PI * currentDegreeFlag / 180)
                    .toFloat() //Math.abs：绝对值 ，Math.PI：表示π ， 弧度 = 度*π / 180
                //            float smallCircleX = (float) Math.abs(Math.sin(arc) * radius + radius - smallRadius / 2 * Math.sin(arc));
//            float smallCircleY = (float) Math.abs(radius - Math.cos(arc) * radius + smallRadius / 2 * Math.cos(arc));
                val smallCircleX =
                    Math.abs(Math.sin(arc.toDouble()) * radius + radius + strokeWidth / 2 + smallCirclePathRadiusPlus)
                        .toFloat()
                val smallCircleY =
                    Math.abs(radius - Math.cos(arc.toDouble()) * radius + strokeWidth / 2 + smallCirclePathRadiusPlus)
                        .toFloat()
                canvas.drawCircle(
                    smallCircleX,
                    smallCircleY,
                    smallRadius,
                    smallCircleSolidePaint!!
                ) //画小圆的实心
            }
        }
    }

    fun setProgress(progress: Long) {
        if (timer != null) {
            timer!!.cancel()
            timer = null
        }
        currentProgress = progress
        //        postInvalidate();
    }

    fun setMax(max: Long) {
        if (timer != null) {
            timer!!.cancel()
            timer = null
        }
        totalProgress = max
        //        postInvalidate();
    }

    fun test() {
        object : CountDownTimer(totalProgress - currentProgress, 200) {
            override fun onTick(millisUntilFinished: Long) {
                currentProgress = totalProgress - millisUntilFinished
                //                Timber.d( "currentProgress = " + currentProgress);
                //刷新view
                postInvalidate()
            }

            override fun onFinish() {
                currentProgress += 50
                //刷新view
                postInvalidate()
            }
        }.start()
    }

    fun trigger() {
        if (timer != null) {
            timer!!.cancel()
            timer = null
        }
        Timber.d("millisInFuture = ${totalProgress - currentProgress}")
        timer = object : CountDownTimer(totalProgress - currentProgress, 200) {
            override fun onTick(millisUntilFinished: Long) {
                currentProgress = totalProgress - millisUntilFinished
                //                Timber.d( "currentProgress = " + currentProgress);
                //刷新view
                postInvalidate()
            }

            override fun onFinish() {
                currentProgress += 200
                //刷新view
                postInvalidate()
            }
        }.start()
    }

    init {
        initAttrs(context, attrs)
        initVariable()
        setLayerType(LAYER_TYPE_SOFTWARE, null)
        smallCircleRadius = 9f.dp / 2f
        smallCirclePadding = 1f.dp
        smallCirclePathRadiusPlus = 5f.dp
    }
}